<script>
import { GlButton, GlFormTextarea } from '@gitlab/ui';
import Tracking from '~/tracking';
import { FEEDBACK_OPTIONS } from 'ee/ai/constants';

// Returns the file extension of a file path, including all segments after the first period
// ex. 'index.html.erb' => 'html.erb'
export const getFileExtension = (file) => file?.match(/(?<=\.)[\w.]+$/)?.at(-1) || '';

export default {
  components: {
    GlButton,
    GlFormTextarea,
  },
  mixins: [Tracking.mixin()],
  props: {
    vulnerability: { type: Object, required: true },
  },
  data() {
    return {
      selectedOption: null,
      comment: '',
      isSubmitted: false,
    };
  },
  computed: {
    feedbackOptions() {
      return this.isSubmitted ? [this.selectedOption] : FEEDBACK_OPTIONS;
    },
  },
  methods: {
    selectFeedback(option) {
      this.selectedOption = option;
    },
    submitFeedback() {
      this.isSubmitted = true;

      this.track('explain_vulnerability', {
        action: 'click_button',
        label: 'response_feedback',
        property: this.selectedOption.value,
        extra: {
          vulnerability_id: this.vulnerability.id,
          identifiers: this.vulnerability.identifiers?.map((i) => i.name),
          file_extension: getFileExtension(this.vulnerability.location?.file),
          severity: this.vulnerability.severity,
        },
      });
    },
  },
};
</script>

<template>
  <div>
    <gl-button
      v-for="option in feedbackOptions"
      :key="option.value"
      class="gl-mr-2"
      :variant="option === selectedOption ? 'confirm' : 'default'"
      :category="option === selectedOption ? 'secondary' : 'primary'"
      :icon="option.icon"
      :disabled="isSubmitted && option === selectedOption"
      data-testid="feedback-button"
      @click="selectFeedback(option)"
    >
      {{ option.title }}
    </gl-button>

    <template v-if="!isSubmitted">
      <gl-form-textarea
        v-model="comment"
        :placeholder="s__('AI|Explain your rating (optional)')"
        class="gl-my-4"
        rows="2"
        max-rows="5"
      />

      <gl-button
        type="submit"
        :disabled="!selectedOption"
        variant="confirm"
        @click="submitFeedback"
      >
        {{ __('Submit') }}
      </gl-button>
    </template>
  </div>
</template>
